package com.moneyanalyzer.sms;

import java.util.Arrays;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;

import com.moneyanalyzer.dao.TransactionDao;
import com.moneyanalyzer.exceptions.BusinessException;
import com.moneyanalyzer.model.Transaction;


public class SmsReceiver extends BroadcastReceiver {

	@Override
	 public void onReceive(Context context, Intent it){
		Log.d("SmsReceiver.onReceive: ", "sms recebido");
		SmsMessage message = SMSUtils.getMessagesFromIntent(it)[0];
		String originatingAddress = message.getOriginatingAddress();
		
		//TODO remover hardcodded bank
		String[] bankNumberArray = {"23700", "11992509610", "11981915508", "011992509610", "011981915508", 
									"+5523700", "+5511992509610", "+5511981915508", "+55011992509610", "+55011981915508"};
		String messageBody = message.getMessageBody();
		
		if(Arrays.asList(bankNumberArray).contains(originatingAddress)){
			Log.d("SmsReceiver.onReceive: ", "Sms interceptado, numero origem :"+originatingAddress);
			Transaction transaction = SMSParser.parser(message);
			TransactionDao dao = TransactionDao.getInstance();
			try {
				dao.insert(transaction, context);
			} catch (BusinessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Toast.makeText(context,
				      "Mensagem recebida de "+
				      originatingAddress + " - "+
				      messageBody,
				      Toast.LENGTH_LONG).show();
		}
		
	    

	}
	
	

}
